package com.xiaozhengkeji.servlet.dao.user;

import com.xiaozhengkeji.servlet.servlet.user.User;
import com.xiaozhengkeji.servlet.tools.INITool;

import java.io.UnsupportedEncodingException;
import java.sql.*;

public class UserLogin {
    private String pathClass = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    private String pathsql;
    private String Sql_JDBC_URL;
    private String Sql_JDBC_USER;
    private String Sql_JDBC_PASSWORD;

    public UserLogin() {
        {
            try {
                pathsql = java.net.URLDecoder.decode(pathClass + "com\\xiaozhengkeji\\servlet\\config\\sqlConfig.ini", "UTF-8");
                this.Sql_JDBC_URL = INITool.getConfig("Sql_JDBC_URL", pathsql);
                this.Sql_JDBC_USER = INITool.getConfig("Sql_JDBC_USER", pathsql);
                this.Sql_JDBC_PASSWORD = INITool.getConfig("Sql_JDBC_PASSWORD", pathsql);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户登陆
     */
    public User userLogin(String username, String password) {
        User u = new User();
        try {
            // 注册JDBC
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection c = DriverManager.getConnection(this.Sql_JDBC_URL, this.Sql_JDBC_USER, this.Sql_JDBC_PASSWORD);
            PreparedStatement ps = null;
            String sql = "SELECT id,user_name,password,form,email FROM servletUser where user_name=? AND password=?";
            ps = c.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = null;
            rs = ps.executeQuery();
            while (rs.next()) {
                u.setID(rs.getString("id"));
                u.setEmail(rs.getString("email"));
                u.setPASSWORD(rs.getString("password"));
                u.setNAME(rs.getString("user_name"));
                u.setFORM(rs.getString("form"));
            }
        } catch (ClassNotFoundException e) {
            u.setNAME("Error:ClassNotFoundException");
            e.printStackTrace();
            return u;
        } catch (SQLException e) {
            u.setNAME("Error:SQLException");
            e.printStackTrace();
            return u;
        }
        return u;
    }
}
